<?php
/**
 * Created by PhpStorm.
 * User: huangj11
 * Date: 2021/1/14
 * Time: 19:36
 */

namespace business\elasticsearch\services;

use business\elasticsearch\repositories\SupplierWordsRepository;
use business\search\models\SupplierWordsModel;
use \business\elasticsearch\models\SupplierWordsModel as ESModel;

class SupplierWordsService
{

    /* @var  $defaultPageSize int  默认分页值 */
    private $defaultPageSize = 500;

    private $isSaveAll = false;

    public function __construct($isSaveAll = false)
    {
        $this->isSaveAll = $isSaveAll;
        $this->createIndex();
    }


    /**
     * 创建索引
     * @return void
     */
    protected function createIndex()
    {
        $repository = new SupplierWordsRepository();
        !$repository->existsIndex() && $repository->createIndex();
    }

    public function saveIndex()
    {
        $wordsCount = $this->getWordsCount();
        echo  'words index count:'.$wordsCount.PHP_EOL;
        if (empty($wordsCount)) {
            return true;
        }
        $pageCount = intval(ceil($wordsCount / $this->defaultPageSize));
        echo  'words index pageIndex:'.$pageCount.PHP_EOL;

        for ($i = 226; $i <= $pageCount; $i++) {
            $items = $this->getWords($i);
            foreach ($items as $item) {
                try {
                    $id = md5($item['uid']);
                    $EsModel = ESModel::findOne($id);
                    if (empty($EsModel)) {
                        $EsModel = new ESModel();
                        $EsModel->primaryKey = $id;
                    }
                    $EsModel->setAttributes($item, false);
                    $EsModel->indexCreatedTime = !empty($jobCreatedTime) ? $jobCreatedTime : date('Y-m-d H:i:s');
                    $rs = $EsModel->save();
                    if (!$rs) {
                        \Yii::error('update es_supplier failed! supplier_id:' . $item['uid']);
                    }
                } catch (\Exception $e) {
                    if (strpos($e->getMessage(), 'Elasticsearch request failed') >=0) {
                        echo $e->getMessage() . PHP_EOL;
                        exit;
                    }
                    echo 'failer supplier words words is ' . $item['uid'] . PHP_EOL;
                }
            }
            echo 'Processed supplier words words words pageIndex ' . $i . PHP_EOL;
        }

        return true;
    }

    private function getWordsCount()
    {
        $query = SupplierWordsModel::find()->where(['is_deleted' => 0]);
        if (!$this->isSaveAll) {
            $query->andWhere('updated_time>=:updated_time',
                [
                    ':updated_time' => $this->getIncreaseMaxTime()
                ]);
        }
        return $query->count();
    }

    public function getWords($index)
    {
        $query = SupplierWordsModel::find()->where(['is_deleted' => 0]);
        if (!$this->isSaveAll) {
            $query->andWhere('updated_time>=:updated_time',
                [
                    ':updated_time' => $this->getIncreaseMaxTime()
                ]);
        }
        $query->offset(intval($index - 1) * $this->defaultPageSize)->limit($this->defaultPageSize);
        $data = $query->orderBy(['uid' => SORT_ASC])->all();
        $result = [];
        if (!empty($data)) {
            foreach ($data as $dv) {
                $tmp = ['uid'=>$dv['uid'], 'word'=>$dv['word'], 'type'=>$dv['type']];
                $result[] = $tmp;
            }
        }
        return $result;
    }

    public function getIncreaseMaxTime()
    {
        return date('Y-m-d H:i:s', strtotime('-1 days', time()));
    }

}